/*
 * aodv_status.cc
 *
 *  Created on: Jan 23, 2014
 *      Author: angelo
 */

#include "../aodv_uu_stimulus.h"

void NS_CLASS status_start() {
    if (status_timer.used)
        return;

    gettimeofday(&this_host.fwd_time, NULL);

    DEBUG(LOG_DEBUG, 0, "Starting to send STATUSs!");
    timer_init(&status_timer, &NS_CLASS status_send, NULL);

    //status_send(NULL);
    //timer_set_timeout(&status_timer, abs(status_interval_ms + normal(0, STATUS_INTERVAL_SIGMA)));
    timer_set_timeout(&status_timer, abs(status_interval_ms + normal(0, (status_interval_ms / 10.0))));
}

void NS_CLASS status_stop() {
    DEBUG(LOG_DEBUG, 0,
            "No active forwarding routes - stopped sending STATUSs!");
#ifdef OMNETPP
    EV << "No active forwarding routes - stopped sending STAUTSs!";
#endif
    timer_remove(&status_timer);
}

RSTATUS_MSG *NS_CLASS rstatus_create( struct in_addr dest_addr, u_int32_t dest_seqno, struct in_addr orig_addr, ManetAddress my_addr) {
    RSTATUS_MSG *pktRis = new RSTATUS_MSG();
    pktRis->type = AODV_RSTATUS;
    pktRis->actual_nInfo = 0;

    return pktRis;
}

void NS_CLASS status_send(void *arg) {

    RSTATUS_MSG *rstatus = NULL;
    struct in_addr dest;
    int msg_size;
    double delay = -1;  //broadcast delay
    struct in_addr dest_addr, orig_addr;

    for (int i = 0; i < MAX_NR_INTERFACES; i++) {
        if (!DEV_NR(i).enabled)
            continue;

        //creating the packet
        rstatus = rstatus_create(DEV_NR(i).ipaddr, this_host.seqno, DEV_NR(i).ipaddr, DEV_NR(i).ipaddr.S_addr);

        /* Immediately before a node originates a RREQ flood it must
               increment its sequence number... */
        seqno_incr(this_host.seqno);

        dest.s_addr = ManetAddress(IPv4Address(AODV_BROADCAST));
        rstatus->ttl=1;
        //rstatus->setName("AodvStatus");
        msg_size = (rstatus->actual_nInfo * sizeof(node_state_info_t)) + 4;
        rstatus->setByteLength(msg_size);

        // send the packet
        aodv_socket_send((AODV_msg *) rstatus, dest, msg_size, 1, &DEV_NR(i),delay);
    }

    //timer_set_timeout(&status_timer, abs(status_interval_ms + normal(0, STATUS_INTERVAL_SIGMA)));
    timer_set_timeout(&status_timer, abs(status_interval_ms + normal(0, (status_interval_ms / 10.0))));
}

void NS_CLASS status_process(RSTATUS_MSG * status, int rstatuslen, unsigned int ifindex) {

}

